package com.xjscrm.console.service.customer.childUser.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.constant.CacheKey;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.MerConfigKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.console.chat.cache.CacheHolder;
import com.xjscrm.console.dto.chat.setting.ChatBaseSettingOptDTO;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.user.*;
import com.xjscrm.console.service.customer.childUser.ChildMerchatService;
import com.xjscrm.console.service.customer.childUser.StaffService;
import com.xjscrm.console.service.customer.corp.WwCorpService;
import com.xjscrm.console.service.customer.sys.SysConfigService;
import com.xjscrm.console.vo.*;
import com.xjscrm.console.vo.sysconfig.AppFuctionConfigVo;
import com.xjscrm.console.vo.sysconfig.SysBrandConfigVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChildMerchatServiceImpl implements ChildMerchatService {

    @Autowired
    private MerchatChildMapper merchatChildMapper;

    @Autowired
    private MerchatChildDevceRelationMapper merchatChildDevceRelationMapper;

    @Autowired
    private CacheHolder cacheHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StaffGroupMapper staffGroupMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private StaffService staffService;

    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private WwCorpService wwCorpService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addChildMerchat(ChildMerchatDto childMerchatDto) {

        if (childMerchatDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (StringUtils.isBlank(childMerchatDto.getUserName()) || childMerchatDto.getUserName().length() > 10) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.USERNAME_ERROR);
        }
        if (StringUtils.isBlank(childMerchatDto.getUserAccount()) || childMerchatDto.getUserAccount().length() > 20) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.USERACCOUNT_ERROR);
        }
        if (StringUtils.isBlank(childMerchatDto.getPassword())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PASSWORD_NULL);
        }
        if (childMerchatDto.getRoleId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ROLE_NULL);
        }
//        if (childMerchatDto.getGroupId()==null){
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.GROUP_NULL);
//        }
        if (childMerchatDto.getRobotIds() == null || childMerchatDto.getRobotIds().size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ROBOT_NULL);
        }

        //判断账号是否使用
        MerchatChild user = merchatChildMapper.getByAccount(childMerchatDto.getUserAccount(), childMerchatDto.getMerId());
        if (user != null) {
            throw new BusinessException(ResponseCode.ERROR, ResponseMsg.USER_USE);
        }


        //插入子账号
        MerchatChild merchatChild = new MerchatChild();
        BeanUtil.copyProperties(childMerchatDto, merchatChild);
        Long childMerchatID = IdWorker.getId();
        int time = DateUtil.getTime();
        merchatChild.setId(childMerchatID);
        merchatChild.setCreateTime(time);
        merchatChild.setUpdateTime(time);
        merchatChildMapper.insertMerchatChild(merchatChild);

        //插入子账号与机器人中间表
        for (Long robotId : childMerchatDto.getRobotIds()) {
            try {
                MerchatChildDevceRelation merchatChildDevceRelation = new MerchatChildDevceRelation();
                merchatChildDevceRelation.setMerId(childMerchatDto.getMerId());
                merchatChildDevceRelation.setChildMerchatId(childMerchatID);
                merchatChildDevceRelation.setRobotId(robotId);
                merchatChildDevceRelationMapper.addMerchatChildDevceRelation(merchatChildDevceRelation);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //将子账号和运营商账号存到redis
        redisTemplate.opsForValue().set(String.format(CacheKey.MERCHAT_CHILEMERCHST_RELATION, merchatChild.getUserAccount()), merchatChild.getMerId());

    }


    @Override
    public HashMap<String, Object> updateChildMerchat(ChildMerchatDto childMerchatDto) {
        if (childMerchatDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (childMerchatDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        HashMap<String, Object> map = new HashMap<>();

        MerchatChild merchatChild = merchatChildMapper.getById(childMerchatDto.getId(), childMerchatDto.getMerId());

        if (!merchatChild.getUserAccount().equals(childMerchatDto.getUserAccount())) {
            //判断账号是否使用
            MerchatChild user = merchatChildMapper.getByAccount(childMerchatDto.getUserAccount(), childMerchatDto.getMerId());
            if (user != null) {
                throw new BusinessException(ResponseCode.ERROR, ResponseMsg.USERACCOUNT_EXIST);
            }
            //删除子账号和运营商账号存到redis
            redisTemplate.delete(String.format(CacheKey.MERCHAT_CHILEMERCHST_RELATION, merchatChild.getUserAccount()));

            //将子账号和运营商账号存到redis
            redisTemplate.opsForValue().set(String.format(CacheKey.MERCHAT_CHILEMERCHST_RELATION, childMerchatDto.getUserAccount()), childMerchatDto.getMerId());

            map.put("ifUpdateAccount", 1);
            map.put("oldAccount", merchatChild.getUserAccount());
            map.put("newAccount", childMerchatDto.getUserAccount());
            map.put("merId", childMerchatDto.getMerId());
        } else {
            map.put("ifUpdateAccount", 0);
        }

        //插入子账号与机器人中间表
        MerchatChild child = new MerchatChild();
        BeanUtil.copyProperties(childMerchatDto, child);
        merchatChildMapper.updateChildMerchat(child);

        //当传来的groupId为空时修改分组
        if (childMerchatDto.getGroupId() == null) {
            merchatChildMapper.updateGroupNUll(child.getId(), child.getMerId());
        }


        //查询子账号和机器人关系  删除原关系
        MerchatChildDevceRelationQuery merchatChildDevceRelationQuery = new MerchatChildDevceRelationQuery();
        merchatChildDevceRelationQuery.setMerId(childMerchatDto.getMerId());
        merchatChildDevceRelationQuery.setChildMerchatId(childMerchatDto.getId());
        List<MerchatChildDevceRelation> merchatChildDevceRelationList = merchatChildDevceRelationMapper.getmerchatChildDevceRelation(merchatChildDevceRelationQuery);
        if (merchatChildDevceRelationList != null && !merchatChildDevceRelationList.isEmpty()) {
            for (MerchatChildDevceRelation merchatChildDevceRelation : merchatChildDevceRelationList) {
                cacheHolder.delDeviceStaff(merchatChildDevceRelation.getRobotId(), merchatChildDevceRelation.getChildMerchatId());
                try {
                    merchatChildDevceRelationMapper.deleById(merchatChildDevceRelation.getId(), merchatChildDevceRelation.getMerId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        //插入子账号与机器人中间表
        for (Long robotId : childMerchatDto.getRobotIds()) {
            try {
                MerchatChildDevceRelation merchatChildDevceRelation = new MerchatChildDevceRelation();
                merchatChildDevceRelation.setMerId(childMerchatDto.getMerId());
                merchatChildDevceRelation.setChildMerchatId(childMerchatDto.getId());
                merchatChildDevceRelation.setRobotId(robotId);
                merchatChildDevceRelationMapper.addMerchatChildDevceRelation(merchatChildDevceRelation);

                cacheHolder.addDeviceStaff(robotId, childMerchatDto.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return map;
    }

    @Override
    public ChildMerchantBaseInfoVo getChildMerchantBaseInfo(BaseDto baseDto) {
        if (baseDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        MerchatChild merchatChild = merchatChildMapper.getById(baseDto.getChildId(), baseDto.getMerId());
        if (merchatChild == null) {
            throw new BusinessException(ResponseCode.ERROR, ResponseMsg.USER_USE);
        }
        ChildMerchantBaseInfoVo childMerchantBaseInfoVo = new ChildMerchantBaseInfoVo();
        BeanUtil.copyProperties(merchatChild, childMerchantBaseInfoVo);

        if(childMerchantBaseInfoVo.getRoleId()!=null){
            SysRole sysRole = roleMapper.getById(childMerchantBaseInfoVo.getRoleId(), childMerchantBaseInfoVo.getMerId());
            if(sysRole!=null&&!StringUtils.isBlank(sysRole.getAuthData())){
                childMerchantBaseInfoVo.setAuthData(sysRole.getAuthData());
            }
        }

        SysBrandConfigVo sysBrandConfig = sysConfigService.findSysBrandConfig(baseDto.getMerId());
        if (sysBrandConfig != null) {
            childMerchantBaseInfoVo.setSystemName(sysBrandConfig.getSystemName());
            childMerchantBaseInfoVo.setLogo(sysBrandConfig.getSystemLog());
        }
        childMerchantBaseInfoVo.setShowCorpConfig(wwCorpService.check(merchatChild.getMerId()) ? 0 : 1);
        return childMerchantBaseInfoVo;
    }

    @Override
    public void changechildMerchantHeadImage(ChangeHeadImageDto changeHeadImageDto) {
        if (changeHeadImageDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (changeHeadImageDto.getHeadImage() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (changeHeadImageDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        MerchatChild merchatChild = merchatChildMapper.getById(changeHeadImageDto.getChildId(), changeHeadImageDto.getMerId());
        if (merchatChild == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.USER_UNREG);
        }
        merchatChild.setHeadImage(changeHeadImageDto.getHeadImage());
        merchatChildMapper.updateChildMerchat(merchatChild);
    }

    @Override
    public void addStaffGroup(StaffGroupDto staffGroupDto) {
        if (staffGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (StringUtils.isBlank(staffGroupDto.getGroupName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        StaffGroup staffGroup = new StaffGroup();
        BeanUtil.copyProperties(staffGroupDto, staffGroup);
        staffGroupMapper.addStaffGroup(staffGroup);
    }

    @Override
    public void updateStaffGroup(StaffGroupDto staffGroupDto) {
        if (staffGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (staffGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (StringUtils.isBlank(staffGroupDto.getGroupName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        StaffGroup staffGroup = staffGroupMapper.getById(staffGroupDto.getId(), staffGroupDto.getMerId());
        staffGroup.setGroupName(staffGroupDto.getGroupName());
        staffGroupMapper.updateStaffGroup(staffGroup);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleStaffGroup(StaffGroupDto staffGroupDto) {
        if (staffGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (staffGroupDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        StaffGroup staffGroup = staffGroupMapper.getById(staffGroupDto.getId(), staffGroupDto.getMerId());

        //获取该分组的员工,删除该分组ID
        ChildMerchatQuery childMerchatQuery = new ChildMerchatQuery();
        childMerchatQuery.setMerId(staffGroupDto.getMerId());
        childMerchatQuery.setGroupId(staffGroup.getId());
        List<MerchatChildVo> merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        if (merchatChildVoList != null && !merchatChildVoList.isEmpty()) {
            for (MerchatChildVo merchatChildVo : merchatChildVoList) {
                merchatChildMapper.deleGroupIdById(merchatChildVo.getId(), merchatChildVo.getMerId());
            }
        }
        staffGroupMapper.deleStaffGroupById(staffGroupDto.getId(), staffGroupDto.getMerId());
    }

    @Override
    public Object getStaffList(ChildMerchatQuery childMerchatQuery) {
        if (childMerchatQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        if (childMerchatQuery.getGroupId() != null && childMerchatQuery.getGroupId() != null) {
            if (childMerchatQuery.getGroupId() == 0) {
                childMerchatQuery.setGroupId(null);
            }
            if (childMerchatQuery.getGroupId() != null && childMerchatQuery.getGroupId() == 1) {
                childMerchatQuery.setGroupId(null);
                childMerchatQuery.setIfNullGroup(1);
            }
        }

        String orderBy = OrderByUtil.getOrderBy(childMerchatQuery.getOrderByField(), childMerchatQuery.isAsc());
        PageHelper.startPage(childMerchatQuery.getCurrent(), childMerchatQuery.getSize(), orderBy);
        List<MerchatChildVo> merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        if (merchatChildVoList != null && !merchatChildVoList.isEmpty()) {
            for (MerchatChildVo merchatChildVo : merchatChildVoList) {
                try {
                    //获取分组名
                    StaffGroup staffGroup = staffGroupMapper.getById(merchatChildVo.getGroupId(), merchatChildVo.getMerId());
                    if (staffGroup != null) {
                        merchatChildVo.setGroupName(staffGroup.getGroupName());
                    }
                    //获取角色
                    SysRole sysRole = roleMapper.getById(merchatChildVo.getRoleId(), merchatChildVo.getMerId());
                    if (sysRole != null) {
                        merchatChildVo.setRoleName(sysRole.getRoleName());
                    }
                    //获取机器人
                    List<Long> deviceUniqueIds = new ArrayList<>();
                    List<String> deviceNames = new ArrayList<>();
                    MerchatChildDevceRelationQuery merchatChildDevceRelationQuery = new MerchatChildDevceRelationQuery();
                    merchatChildDevceRelationQuery.setMerId(merchatChildVo.getMerId());
                    merchatChildDevceRelationQuery.setChildMerchatId(merchatChildVo.getId());
                    List<MerchatChildDevceRelation> merchatChildDevceRelationList = merchatChildDevceRelationMapper.getmerchatChildDevceRelation(merchatChildDevceRelationQuery);
                    if (merchatChildDevceRelationList != null && !merchatChildDevceRelationList.isEmpty()) {
                        for (MerchatChildDevceRelation merchatChildDevceRelation : merchatChildDevceRelationList) {
                            WwDevice wwDevice = wwDeviceMapper.getById(merchatChildDevceRelation.getRobotId(), merchatChildDevceRelationQuery.getMerId());
                            if (wwDevice != null) {
                                deviceUniqueIds.add(wwDevice.getId());
                                deviceNames.add(wwDevice.getDeviceName());
                            }

                        }
                    }
                    merchatChildVo.setDeviceUniqueIds(deviceUniqueIds);
                    merchatChildVo.setDeviceNames(deviceNames);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        MyPageInfo<MerchatChildVo> merchatChildVoMyPageInfo = new MyPageInfo<>(merchatChildVoList);
        return merchatChildVoMyPageInfo;
    }

    @Override
    public void chageGroup(ChageGroupDto chageGroupDto) {
        if (chageGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (chageGroupDto.getStaffId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (chageGroupDto.getGroupId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        MerchatChild merchatChild = merchatChildMapper.getById(chageGroupDto.getStaffId(), chageGroupDto.getMerId());
        merchatChild.setGroupId(chageGroupDto.getGroupId());
        merchatChildMapper.updateChildMerchat(merchatChild);
    }

    @Override
    @Async("taskExecutor")
    public void batchchageGroup(ChageGroupDto chageGroupDto) {
        if (chageGroupDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (chageGroupDto.getGroupId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (chageGroupDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (chageGroupDto.getType() == 0 && (chageGroupDto.getStaffIds() == null || chageGroupDto.getStaffIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (chageGroupDto.getType() == 0) {
            batchchageGroupBySelct(chageGroupDto);
        }
        if (chageGroupDto.getType() == 1) {
            batchchageGroupAll(chageGroupDto);
        }

    }

    private void batchchageGroupBySelct(ChageGroupDto chageGroupDto) {
        for (Long staffId : chageGroupDto.getStaffIds()) {
            try {
                chageGroupDto.setStaffId(staffId);
                chageGroup(chageGroupDto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void batchchageGroupAll(ChageGroupDto chageGroupDto) {
        //查询出所有的子账号
        ChildMerchatQuery childMerchatQuery = chageGroupDto.getChildMerchatQuery();
        Long idStart = 0L;
        childMerchatQuery.setMerId(chageGroupDto.getMerId());
        childMerchatQuery.setAsc(true);
        childMerchatQuery.setCurrent(1);
        childMerchatQuery.setSize(100);
        childMerchatQuery.setOrderByField("id");
        childMerchatQuery.setIdStart(idStart);
        String orderBy = OrderByUtil.getOrderBy(childMerchatQuery.getOrderByField(), childMerchatQuery.isAsc());
        PageHelper.startPage(childMerchatQuery.getCurrent(), childMerchatQuery.getSize(), orderBy);
        List<MerchatChildVo> merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        while (merchatChildVoList != null && !merchatChildVoList.isEmpty()) {
            for (MerchatChildVo merchatChildVo : merchatChildVoList) {
                try {
                    if (merchatChildVo.getId().longValue() > idStart.longValue()) {
                        idStart = merchatChildVo.getId();
                    }
                    chageGroupDto.setStaffId(merchatChildVo.getId());
                    chageGroup(chageGroupDto);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            childMerchatQuery.setIdStart(idStart);
            PageHelper.startPage(childMerchatQuery.getCurrent(), childMerchatQuery.getSize(), orderBy);
            merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        }

    }

    @Override
    public Object getStaffGroupList(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        ArrayList<Map> mapArrayList = new ArrayList<>();

        //获取所有子账号
        ChildMerchatQuery childMerchatQuery = new ChildMerchatQuery();
        childMerchatQuery.setMerId(baseDto.getMerId());
        List<MerchatChildVo> merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        HashMap<String, Object> allChildMerchatMap = new HashMap<>();
        allChildMerchatMap.put("id", 0);
        allChildMerchatMap.put("name", "全部分组");
        allChildMerchatMap.put("number", merchatChildVoList.size());
        mapArrayList.add(allChildMerchatMap);


        StaffGroupQuery staffGroupQuery = new StaffGroupQuery();
        staffGroupQuery.setMerId(baseDto.getMerId());
        List<StaffGroupDtoVo> staffGroupDtoVoList = staffGroupMapper.getStaffGroup(staffGroupQuery);
        List<Long> exsitGroupId = new ArrayList<>();
        staffGroupDtoVoList.forEach(it -> exsitGroupId.add(it.getId()));

        //获取未分组的子账号
        List<MerchatChildVo> collect = merchatChildVoList.stream().filter(it -> !exsitGroupId.contains(it.getGroupId())).collect(Collectors.toList());
        HashMap<String, Object> absentDeviceMap = new HashMap<>();
        absentDeviceMap.put("id", 1);
        absentDeviceMap.put("name", "未分组");
        absentDeviceMap.put("number", collect.size());
        mapArrayList.add(absentDeviceMap);


        for (StaffGroupDtoVo staffGroupDtoVo : staffGroupDtoVoList) {
            try {
                HashMap<String, Object> map = new HashMap<>();
                ChildMerchatQuery merchatQuery = new ChildMerchatQuery();
                merchatQuery.setMerId(staffGroupDtoVo.getMerId());
                merchatQuery.setGroupId(staffGroupDtoVo.getId());
                List<MerchatChildVo> merchatChildVos = merchatChildMapper.getMerchatChild(merchatQuery);
                map.put("id", staffGroupDtoVo.getId());
                map.put("name", staffGroupDtoVo.getGroupName());
                map.put("number", merchatChildVos.size());
                mapArrayList.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mapArrayList;
    }

    @Override
    public Object getStaffGroupDropDwon(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        ArrayList<Map> mapArrayList = new ArrayList<>();

        StaffGroupQuery staffGroupQuery = new StaffGroupQuery();
        staffGroupQuery.setMerId(baseDto.getMerId());
        List<StaffGroupDtoVo> staffGroupDtoVoList = staffGroupMapper.getStaffGroup(staffGroupQuery);
        for (StaffGroupDtoVo staffGroupDtoVo : staffGroupDtoVoList) {
            try {
                HashMap<String, Object> map = new HashMap<>();
                map.put("value", staffGroupDtoVo.getId());
                map.put("label", staffGroupDtoVo.getGroupName());
                mapArrayList.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return mapArrayList;
    }

    @Override
    public MerchatChild getById(ChildMerchatDto param) {
        if (Objects.isNull(param)) {
            return null;
        }

        return this.merchatChildMapper.getById(param.getId(), param.getMerId());
    }

    @Override
    public List<String> batchDeleStaff(BatchDeleStaffDto batchDeleStaffDto) {
        if (batchDeleStaffDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchDeleStaffDto.getSelectType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchDeleStaffDto.getSelectType() == 0 && (batchDeleStaffDto.getIds() == null || batchDeleStaffDto.getIds().isEmpty())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        if (batchDeleStaffDto.getSelectType() == 0) {
            List<String> list = batchDeleStaffBySelect(batchDeleStaffDto);
            return list;
        }
        if (batchDeleStaffDto.getSelectType() == 1) {
            List<String> list = batchDeleStaffAll(batchDeleStaffDto);
            return list;
        }
        return null;
    }

    @Override
    @Transactional
    public void batchEditChatLimitCount(LoginVO login, StaffBatchOptDto staffBatchOptDto) {

        List<MerchatChild> merchatChildList = merchatChildMapper.selectByIds(login.getMerId(), staffBatchOptDto.getIds());

        if (ObjectUtils.isEmpty(merchatChildList)) {
            return;
        }

        for (MerchatChild merchatChild : merchatChildList) {
            merchatChild.setChatLimitCount(staffBatchOptDto.getChatLimitCount());
            merchatChild.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
            merchatChildMapper.updateChildMerchat(merchatChild);

            cacheHolder.setStaffSessionCount(login.getMerId(), merchatChild.getId(), staffBatchOptDto.getChatLimitCount());
        }
    }

    private List<String> batchDeleStaffBySelect(BatchDeleStaffDto batchDeleStaffDto) {
        List<String> userAccounts = new ArrayList<>();
        for (Long id : batchDeleStaffDto.getIds()) {
            try {
                MerchatChild merchatChild = merchatChildMapper.getById(id, batchDeleStaffDto.getMerId());
                userAccounts.add(merchatChild.getUserAccount());
                batchDeleStaffDto.setId(id);
                staffService.deleStaffBySelect(batchDeleStaffDto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return userAccounts;
    }


    private List<String> batchDeleStaffAll(BatchDeleStaffDto batchDeleStaffDto) {
        //查询出所有的子账号
        ChildMerchatQuery childMerchatQuery = batchDeleStaffDto.getChildMerchatQuery();
        Long idStart = 0L;
        childMerchatQuery.setMerId(batchDeleStaffDto.getMerId());
        childMerchatQuery.setAsc(true);
        childMerchatQuery.setCurrent(1);
        childMerchatQuery.setSize(100);
        childMerchatQuery.setOrderByField("id");
        childMerchatQuery.setIdStart(idStart);
        String orderBy = OrderByUtil.getOrderBy(childMerchatQuery.getOrderByField(), childMerchatQuery.isAsc());
        PageHelper.startPage(childMerchatQuery.getCurrent(), childMerchatQuery.getSize(), orderBy);
        List<MerchatChildVo> merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        List<String> userAccounts = new ArrayList<>();
        while (merchatChildVoList != null && !merchatChildVoList.isEmpty()) {
            for (MerchatChildVo merchatChildVo : merchatChildVoList) {
                try {
                    if (merchatChildVo.getId().longValue() > idStart.longValue()) {
                        idStart = merchatChildVo.getId();
                    }
                    userAccounts.add(merchatChildVo.getUserAccount());
                    batchDeleStaffDto.setId(merchatChildVo.getId());
                    staffService.deleStaffBySelect(batchDeleStaffDto);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            childMerchatQuery.setIdStart(idStart);
            PageHelper.startPage(childMerchatQuery.getCurrent(), childMerchatQuery.getSize(), orderBy);
            merchatChildVoList = merchatChildMapper.getMerchatChild(childMerchatQuery);
        }
        return userAccounts;

    }

    @Override
    public Object getPppPwd(@MerId Long merId) {
        AppFuctionConfigVo appFuctionConfigVo = new AppFuctionConfigVo();

        //查询运营商品牌设置信息
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.APP_FUCTION_CONFIG.getValue());
        if (merBaseConfig != null) {
            appFuctionConfigVo = JSONObject.parseObject(merBaseConfig.getVal(), AppFuctionConfigVo.class);
        }

        if (appFuctionConfigVo == null || appFuctionConfigVo.getLoginPassword() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "app密码为空");
        }

        return appFuctionConfigVo.getLoginPassword();
    }

    @Override
    public MerchatChild getById(@MerId Long merId, Long id) {

        return merchatChildMapper.getById(id, merId);
    }

    @Override
    public Boolean editChatNotice(LoginVO login, ChatBaseSettingOptDTO openNotice) {

        MerchatChild update = new MerchatChild();
        update.setId(login.getId());
        update.setChatOpenNotice(openNotice.getOpenNotice());
        update.setChatOpenGroupNotice(openNotice.getOpenGroupNotice());
        update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));

        merchatChildMapper.updateByPrimaryKeySelective(update);

        return true;
    }

    @Override
    public List<MerchatChild> listByIds(@MerId Long merId, List<Long> ids) {
        return merchatChildMapper.selectByIds(merId, ids);
    }

    @Override
    public List<MerchatChild> listByIdsAndGroupId(@MerId Long merId, List<Long> ids, Long groupId) {

        return merchatChildMapper.selectByIdsAndGroupId(merId, ids, groupId);
    }
}
